<?php
class LZ_Item
{
	var $table = 'item';
	var $id = 'item_id';
	var $category_id = 'category_id';
	var $name = 'name';
	var $description = 'description';
	var $user_id = 'user_id';
	var $view_count = 'view_count';
	
	function LZ_Item()
	{
		$this->table = LZ_MYSQL_PREFIX.$this->table;
	}

	function add( $data = array())
	{
		global $db;
		$sql = make_insert_sql($this->table,$data); 
		if ($db->query($sql))
		{
			$this->update_html($db->insert_id());
			return true;
		}
		else
			return false;
	}
	
	function delete($item_id)
	{
		global $db;
		$item = $this->get_one($item_id);
		$sql = "DELETE FROM $this->table WHERE $this->id = '$item_id'";
		if ($db->query($sql))
		{
			$this->update_html($item_id);
			return lz_delete($item['url']);
		}
		else
			return false;
	}
	
	function update( $id, $data = array())
	{
		global $db;
		if ($data['url_name'])
		{
			$old_item = $this->get_one($id);
			$data['url'] = get_item_path(
				array(
					'url_name'=>$data['url_name'],
					'publish_time'=>$old_item['publish_time']
				)
			);
		}
		$sql = make_update_sql($this->table,$data, array('item_id' => $id)); 
		if ($db->query($sql))
		{
			$this->update_html($id);
			if ($data['url_name'] && $data['url_name'] != $old_item['url_name'])
			{
				$old_path = get_item_path(
					array(
						'url_name'=>$old_item['url_name'],
						'publish_time'=>$old_item['publish_time']
					)
				);
				lz_mv($old_path,$data['url']);
			}
			return true;
		}
		else return false;
	}

	function update_html($id)
	{
		lz_update(); //update index
		include_once(LZ_BASEPATH.'model/category.php');
		$item = $this->get_one($id);
		lz_update($item['url']);
		$category = new LZ_Category;
		$category->update_html($item['category_id']);
	}
	
	function get_one($id)
	{
		global $db;
		$sql = "SELECT * FROM `{$this->table}` WHERE `{$this->id}` = '$id' LIMIT 1";
		return $db->get_one($sql);
	}

	function get_list($data=array())
	{
		global $db;
		$_s = $data['select']?$data['select']:'*';
		$sql = "SELECT $_s FROM `{$this->table}` WHERE 1=1 ";
		if ($data['search'])
			$sql.=" AND (`$this->name` LIKE '%".$data['search']."%' OR `$this->description` LIKE '%".$data['search']."%' )";
		
		if ($data['category_id']) $sql.=" AND $this->category_id = '".$data['category_id']."' ";
				
		if (isset($data['category_ids'])) $sql.=" AND $this->category_id IN (".$data['category_ids'].") ";
				
		if (!$data['order'])
			$sql.= " ORDER BY order_id DESC,`publish_time` DESC";		
		else
			$sql.= " ORDER BY `".$data['order'].'`';
		
		if ($data['from'] && $data['total'])
			$sql.=" LIMIT ".$data['from'].",".$data['total'];
		else if ($data['total'])
			$sql.=" LIMIT ".$data['total'];
			
		$sql.= ';';
		return $db->get_all($sql);
	}
}
?>